<?php

namespace Icsoc\NoticeBundle\Controller;

use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Icsoc\SecurityBundle\Entity\CcAnnouncement;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 公告管理
 * Class NoticeController
 * @package Icsoc\NoticeBundle\Controller
 */
class NoticeController extends BaseController
{
    /**
     * @return Response
     */
    public function indexAction()
    {
        return $this->render("IcsocNoticeBundle:Notice:index.html.twig");
    }

    /**
     * 公告列表
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        $where = ' AND intro.vccId = :vcc_id ';
        $parameter['vcc_id']  = $this->getUser()->getVccId();
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['keyword']) && !empty($json['keyword'])) {
                $where.="AND intro.title like '%".$json['keyword']."%'";
            }
        }

        /** @var \Doctrine\ORM\EntityManagerInterface $em */
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery(
            "SELECT count(intro)
            FROM IcsocSecurityBundle:CcAnnouncement intro
            WHERE 1=1 ".$where
        )->setParameters($parameter);
        try {
            $single = $query->getSingleResult();
            $count = $single['1'];
        } catch (NoResultException $e) {
            $count = 0;
        }
        if ($count > 0) {
            $totalPage = ceil($count/$rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page -1 )*$rows;

        /** @var \Doctrine\ORM\Query $query */
        $query = $em->createQuery(
            "SELECT intro
            FROM IcsocSecurityBundle:CcAnnouncement intro
            WHERE 1=1 {$where}
            ORDER BY intro.".$sidx.' '.$sord
        )->setParameters($parameter);

        $query->setFirstResult($start);
        $query->setMaxResults($rows);
        $all = $query->getArrayResult();
        foreach ($all as $key => $v) {
            $all[$key]['addTime'] = date('Y-m-d H:i:s', $v['addTime']);
            $all[$key]['startDate'] = $v['startDate']->format("Y-m-d");
            $all[$key]['endDate'] = $v['endDate']->format("Y-m-d");
            $all[$key]['content'] = mb_substr(strip_tags($v['content']), 0, 10, 'utf-8');
        }
        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $count;
        $serializer = $this->get('serializer');
        $response = $serializer->serialize($reponse, 'json');

        return new Response($response);
    }

    /**
     * 添加公告
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function addAction(Request $request)
    {
        $notice = new CcAnnouncement();
        $form = $this->createForm('notice_info_form', $notice);
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $notice->setStartDate(new \DateTime($notice->getStartDate()));
                $notice->setEndDate(new \DateTime($notice->getEndDate()));
                $notice->setVccId($this->getUser()->getVccId());
                $notice->setAddTime(time());
                $em->persist($notice);
                $em->flush();
                $logStr = $this->get('translator')->trans('Add notice %str%', array('%str%'=>$notice->getTitle()));
                $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, $logStr);
                $data = array(
                    'data'=>array(
                        'msg_detail'=> $this->get('translator')->trans('Add announcement success'),
                        'type'=>'success',
                        'link' => array(
                            array(
                                'text'=>$this->get('translator')->trans('Continue to add announcement'),
                                'href'=>$this->generateUrl('icsoc_notice_add'),
                            ),
                            array(
                                'text'=>$this->get('translator')->trans('Announcement list'),
                                'href'=>$this->generateUrl('icsoc_notice_index'),
                            ),
                        ),
                    ),
                );

                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }

        return $this->render("IcsocNoticeBundle:Notice:noticeInfo.html.twig", array(
                'form' => $form->createView(),
            ));
    }

    /**
     * 编辑公告
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function editAction(Request $request)
    {
        $id = $request->get('id', '');
        $em = $this->getDoctrine()->getManager();
        /** @var \Icsoc\SecurityBundle\Entity\CcAnnouncement $notice */
        $notice = $em->getRepository('IcsocSecurityBundle:CcAnnouncement')->find($id);
        /** @var \DateTime $startDate */
        $startDate = $notice->getStartDate()->format('Y-m-d');
        /** @var \DateTime $endDate */
        $endDate = $notice->getEndDate()->format('Y-m-d');
        $notice->setStartDate($startDate);
        $notice->setEndDate($endDate);
        $form = $this->createForm('notice_info_form', $notice);
        $oldNotice = array('title'=>$notice->getTitle(), 'start_date'=>$startDate, 'end_date'=>$endDate);
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $notice->setStartDate(new \DateTime($notice->getStartDate()));
                $notice->setEndDate(new \DateTime($notice->getEndDate()));
                $notice->setAddTime(time());
                $em->flush();
                $newNotice = array('title'=>$notice->getTitle(), 'start_date'=>$startDate, 'end_date'=>$endDate);
                $diff = array_diff_assoc($oldNotice, $newNotice);
                $logStr = '';
                foreach ($diff as $k => $v) {
                    $logStr.="[".$k."]:".$oldNotice[$k]."=>".$newNotice[$k]." ";
                }
                if (!empty($logStr)) {
                    $logStr = $this->get('translator')->trans('Edit notice %str%', array('%str%'=>$logStr));
                    $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_UPDATE, $logStr);
                }
                $data = array(
                    'data'=>array(
                        'msg_detail'=> $this->get('translator')->trans('Edit announcement success'),
                        'type'=>'success',
                        'link' => array(
                            array(
                                'text'=>$this->get('translator')->trans('return'),
                                'href'=>'javascript:history.go(-1);',
                            ),
                            array(
                                'text'=>$this->get('translator')->trans('Announcement list'),
                                'href'=>$this->generateUrl('icsoc_notice_index'),
                            ),
                        ),
                    ),
                );

                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }

        return $this->render("IcsocNoticeBundle:Notice:noticeInfo.html.twig", array(
                'form' => $form->createView(),
            ));
    }

    /**
     * 删除公告；
     * @param Request $request
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $ids = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        $em->createQuery(
            "DELETE FROM IcsocSecurityBundle:CcAnnouncement c
            WHERE c.id IN ($ids) AND c.vccId = :vcc_id"
        )->setParameter('vcc_id', $this->getVccId())->execute();
        $logStr = $this->get('translator')->trans('Delete notice %str%', array('%str%'=>$ids));
        $this->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_DELETE, $logStr);
        $em->flush();

        return new JsonResponse(array('message'=>$this->get('translator')->trans('Delete success'), 'error'=>0));
    }

    /**
     * 查看公告
     * @param Request $request
     * @return Response
     */
    public function showAction(Request $request)
    {
        $id = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        /** @var \Icsoc\SecurityBundle\Entity\CcAnnouncement $info */
        $info = $em->getRepository("IcsocSecurityBundle:CcAnnouncement")->find($id);
        if (!empty($info)) {
            $info->setVisittimes($info->getVisittimes()+1);
            $em->flush();
        } else {
            $info = array('title'=>'该公告已经删除', 'content'=>'');
        }

        return $this->render("IcsocNoticeBundle:Notice:show.html.twig", array(
                'info' => $info,
            ));
    }
}
